using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class MeshBoundingBox //: ScriptableObject
{
    private Transform body;
    private Vector3 centerOffset;
    private Vector3 halfSize;
    private Vector3[] localPoints;

    public MeshBoundingBox(Transform body, Vector3 center, Vector3 halfSize)
    {
        this.body = body;
        this.centerOffset = center - body.position;
        this.halfSize = halfSize;
        this.localPoints = new Vector3[]
            {
                halfSize,
                new Vector3(-halfSize.x, halfSize.y , halfSize.z),
                new Vector3(halfSize.x, -halfSize.y , halfSize.z),
                new Vector3(halfSize.x, halfSize.y , -halfSize.z),
                new Vector3(-halfSize.x, -halfSize.y , halfSize.z),
                new Vector3(halfSize.x, -halfSize.y , -halfSize.z),
                new Vector3(-halfSize.x, halfSize.y , -halfSize.z),
                halfSize,
            };
    }

    public Rect GetScreenRect() 
    {
        Rect rect = new Rect();
        float xMin = float.MaxValue, xMax = float.MinValue, yMin = float.MaxValue, yMax = float.MinValue;
        Vector3[] worldVertex = GetWorldBoundingPoints();
        for (int i = 0; i < worldVertex.Length; i++)
        {
            Vector3 screenVertex = Camera.main.WorldToScreenPoint(worldVertex[i]);
            if (screenVertex.x < xMin)
            {
                xMin = screenVertex.x;
            }
            if (screenVertex.x > xMax)
            {
                xMax = screenVertex.x;
            }
            if (screenVertex.y < yMin)
            {
                yMin = screenVertex.y;
            }
            if (screenVertex.y > yMax)
            {
                yMax = screenVertex.y;
            }
        }

        rect = Rect.MinMaxRect(xMin, yMin, xMax, yMax);

        return rect;
    }

    public Vector3[] GetWorldBoundingPoints() 
    {
        Vector3[] worldVertex = new Vector3[8];
        for (int i = 0; i < 8; i++)
        {
            worldVertex[i] = body.position + centerOffset + localPoints[i];
        }
        return worldVertex;
    }

    public void DrawBoundingBox()
    {
        Vector3[] worldVertex = GetWorldBoundingPoints();
        for (int i = 0; i < worldVertex.Length; i++)
        {
            Gizmos.DrawSphere(worldVertex[i], 0.05f);
        }

        Gizmos.DrawWireCube(body.position + centerOffset, halfSize * 2);
    }
}
